package com.peak.distribution.tools;

import java.util.List;
import java.util.Map;
import java.util.Random;

import com.fasterxml.jackson.databind.JavaType;
import com.google.common.collect.Maps;
import com.peak.distribution.exception.DistributionError;
import com.peak.distribution.exception.DistributionException;
import com.peak.spring.boot.core.mapper.JsonMapper;
import com.peak.spring.boot.tools.Converts;
import com.peak.spring.boot.tools.Emptys;
import com.peak.spring.boot.tools.HttpClients;

import lombok.Data;

public class Kuaidi100Tools {

	public static KuaidiPost query(String waybillNo) {
		Map<String, String> param = Maps.newHashMap();
		JsonMapper jsonMapper = JsonMapper.nonDefaultMapper();
		JavaType comType = jsonMapper.contructCollectionType(List.class, KuaidiCompany.class);
		param.put("num", waybillNo);
		String comResult = HttpClients.get("https://m.kuaidi100.com/autonumber/auto", param);
		List<KuaidiCompany> com  = jsonMapper.fromJson(comResult, comType);
		if (Emptys.isEmpty(com)) {
			throw new DistributionException(DistributionError.KUAI_DI_QUERY_FAIL);
		}
		String comCode = com.get(0).getComCode();
		if (Emptys.isEmpty(comCode)) {
			throw new DistributionException(DistributionError.KUAI_DI_QUERY_FAIL);
		}
		param.clear();
		param.put("type", comCode);
		param.put("postid", waybillNo);
		param.put("id", "1");
		param.put("valicode", "");
		param.put("temp", Converts.toString(new Random().nextDouble()));
		String postResult = HttpClients.get("https://m.kuaidi100.com/query", param);
		KuaidiPost post = jsonMapper.fromJson(postResult, KuaidiPost.class);
		post.setStateMessage(KuaidiState.values()[Converts.toInt(post.getState())].getValue());
		return post;
	}
	
	@Data
	public static class KuaidiCompany {
		private String comCode;
		private String id;
		private String noCount;
		private String noPre;
		private String startTime;
	}
	
	@Data
	public static class KuaidiPost {
		private String com;
		private String condition;
		private String ischeck;
		private String message;
		private String nu;
		private String state;
		private String stateMessage;
		private String status;
		private List<KuaidiData> data;
	}
	
	@Data
	public static class KuaidiData {
		private String context;
		private String ftime;
		private String location;
		private String time;
	}
	
	public enum KuaidiState {
		ZAI_TU("在途")
		, LAN_JIAN("揽件")
		, YI_NAN("疑难")
		, QIAN_SHOU("签收")
		, TUI_QIAN("退签")
		, PAI_JIAN("派件")
		, TUI_HUI("退回")
		;
		private String value;
		
		KuaidiState(String value) {
			this.value = value;
		}

		public String getValue() {
			return value;
		}
	}
}
